package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.qf.entity.Orders;
import com.qf.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private IOrderService orderService;

    /**
     * 进行支付宝支付
     * @param oid
     * @return
     */
    @RequestMapping("/alipay")
    public void alipay(String oid, HttpServletResponse response){
        System.out.println("接收到支付的请求：" + oid);

        //通过订单号搜索订单详情
        Orders orders = orderService.getById(oid);

        //调用支付宝支付
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                "2016073000127352",//appid
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDqUDtKCYMgH55YyldhVsLW+IiiYuq9DmRh97gfaLD0PcrIMeSTKsosjrlcEa6HgjP2uLq+eK/sR+RC16fR1l9Lzx5JvHASvhtNTdYTv9igWFIJjeVnuLD98Y3kmAjw+a4igFu6TacnU9PHgpcZcHjyKM3cEZfCffYObKtTjcAMbh0zC9OZSD6YOr6ceaQhyo/1WK0rJTubMiBfCsUzzZDivvpUlVBbvIfbtRBYu8uhPCHMFk6dQ9WFxYKI7t9VVMMgTZb4zLzXFBmXtmJlcW2vgs8ZpQHUHBxiYHU4+8TJn/kbHc883yS9CVhMd1aDb5LKk/Yvsy4YxjVTNxkzaQvdAgMBAAECggEABSJU6j5jHSUUNyXX3E4mXsd7VvOL6TCTioH/CtEkb3WbJ9/P/lmFrIxEC3xnsphrwxAxJ1NFp4u7uKs5BiQIWoTjSQJUAlUgDAWUl0Iw4PKOeZ8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QdA=",//应用私钥
                "json",
                "UTF-8",
                "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIgHnOn7LLILlKETd6BFRJ0GqgS2Y3mn1wMQmyh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB",//阿里公钥
                "RSA"); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://www.baidu.com");//同步请求，支付成功后，用户的页面跳转到哪里？
        alipayRequest.setNotifyUrl("http://verygoodwlk.xicp.net/pay/payResult");//异步请求，支付完成后，支付结果告知的url

        //支付的参数申请
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":\"" + oid + "\"," +
                " \"total_amount\":\"" + orders.getAllPrice() + "\"," +
                " \"subject\":\"" + oid + "\"," +
                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");//填充业务参数
        String form="";
        try {
            //发送支付请求给支付宝
            //返回一个支付页面的form表单
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 支付的结果处理方法
     * @return
     */
    @RequestMapping("/payResult")
    public String payResult(HttpServletRequest request){
        System.out.println("支付的结果返回，支付结果：");

        //获得请求所有参数的map集合
        Map<String, String[]> parameterMap = request.getParameterMap();

        //支付结果的验签
        Map<String, String> paramsMap = new HashMap<>(); //将异步通知中收到的所有参数都存放到map中

        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            paramsMap.put(entry.getKey(), entry.getValue()[0]);
        }


        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                    "MIGfMA0GCS" +
                            "qGSIb3DQEBAQUAA4GNADCBiQKBgQDIgHnOn7LLILlKETd6BFRJ0GqgS2Y3mn1wMQmyh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB",//阿里公钥,
                    "UTF-8",
                    "RSA");//调用SDK验证签名
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println("验签通过，该请求是支付宝发送的请求！");
            //二次验签
//            if(){
//                //判断交易状态
//               if(){
//                   //修改订单状态
//               }
//            }

            return "success";

        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            System.out.println("验签失败，该请求为异常请求！");
        }

        return "failure";
    }
}
